@echo off
setlocal

:: 执行 npm run build
echo Running npm run build...
call npm run build

if errorlevel 1 (
    echo Failed to build project.
    exit /b 1
)

:: 设置变量
set DIST_DIR=dist
set ZIP_FILE=dist.zip
set REMOTE_USER=root
set REMOTE_HOST=192.168.111.85
set REMOTE_PATH=/opt/fengbo/ui/map/
set SEVEN_ZIP_PATH=D:\Program Files\7-Zip\7z.exe
set SCP_PATH=scp
set SSH_PATH=ssh
set PRIVATE_KEY_PATH=D:\ssh\id_rsa

:: 压缩 dist 目录
echo Compressing %DIST_DIR% to %ZIP_FILE%...
call "%SEVEN_ZIP_PATH%" a -tzip "%ZIP_FILE%" "%DIST_DIR%"

if errorlevel 1 (
    echo Failed to compress %DIST_DIR%.
    exit /b 1
)

:: 上传压缩文件到远程服务器
echo Uploading %ZIP_FILE% to %REMOTE_HOST%:%REMOTE_PATH%...
call "%SCP_PATH%" -i "%PRIVATE_KEY_PATH%" "%ZIP_FILE%" %REMOTE_USER%@%REMOTE_HOST%:%REMOTE_PATH%

if errorlevel 1 (
    echo Failed to upload %ZIP_FILE%.
    exit /b 1
)

:: 删除本地 dist 目录
:: echo Deleting local %DIST_DIR% directory...
:: rmdir /s /q "%DIST_DIR%"

if errorlevel 1 (
    echo Failed to delete local %DIST_DIR% directory.
    exit /b 1
)

:: 解压远程服务器上的 zip 文件
echo Unzipping %ZIP_FILE% on remote server...
call "%SSH_PATH%" -i "%PRIVATE_KEY_PATH%" %REMOTE_USER%@%REMOTE_HOST% "cd %REMOTE_PATH% && unzip -o %ZIP_FILE%"

if errorlevel 1 (
    echo Failed to unzip %ZIP_FILE% on remote server.
    exit /b 1
)

:: 删除远程服务器上的 zip 文件
echo Deleting remote %ZIP_FILE%...
call "%SSH_PATH%" -i "%PRIVATE_KEY_PATH%" %REMOTE_USER%@%REMOTE_HOST% "rm %REMOTE_PATH%/%ZIP_FILE%"

if errorlevel 1 (
    echo Failed to delete remote %ZIP_FILE%.
    exit /b 1
)

:: 删除本地 zip 文件
echo Deleting local %ZIP_FILE%...
del "%ZIP_FILE%"

if errorlevel 1 (
    echo Failed to delete local %ZIP_FILE%.
    exit /b 1
)

echo All tasks completed successfully.

endlocal